<?php

namespace app\api\service;

use app\admin\model\Shop;
use app\common\model\Business;
use app\common\model\BusinessWalletLog;
use app\admin\model\Play;
use think\Db;
use think\Exception;

/**
 * 活动
 * Class PlayService
 * @package app\api\service
 */
class PlayService extends BaseService
{
    public function getPlayList($where, $lat, $lng, $order = "distance asc,id desc", $page = 1,$high_rebate,$snatchable, $pageSize = 10, $extend = [], $is_collection=0)
    {
        if (!isset($where['g.play_type'])) {
            $where['g.play_type'] = ['in',[1,3]];
        }
        $nowDateTime = time();
        $nowTime = $nowDateTime - strtotime(date("Y-m-d 00:00:00", $nowDateTime));
        // $field = "g.*,s.logo_pic,s.id as s_id,s.shop_name as s_name,s.shop_type as s_type,s.phone,s.lat,s.lng,s.address,s.shop_status as s_status,round((6378.138 * 2 * asin(sqrt(pow(sin((s.lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(s.lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((s.lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000)/1,1) as distance";
        $field = "g.*,s.id as s_id,s.logo_pic,s.shop_name as s_name,s.shop_type as s_type,s.phone,s.lat,s.lng,s.address,s.shop_status as s_status,10000*(abs(s.lng-".$lng.")+abs(s.lat -".$lat.")) as distance,s.dpzxelm";
        $map = [
            'g.play_status' => ['=', 2],
            'g.start_date' => ['<=', $nowDateTime],
            'g.end_date' => ['>=', $nowDateTime],
            's.shop_status' => ['=', '1'],
        ];
        $map = array_merge($map, $where);
        if ($high_rebate) {
            if ($snatchable) {
                $list = Db::name('play')->alias('g')
                    ->join('chbc_shop s', "g.shop_no=s.shop_no")
                    ->field($field)
                    ->where($map)
                    ->where('g.user_pay-g.back_money<=5')
                    ->where('CONCAT_WS(" ",DATE_FORMAT(NOW(),"%Y-%m-%d"),g.end_time_str)>="'.date('Y-m-d H:i').'"')
                    ->order($order)
                    ->group('g.shop_no')
                    ->page($page, $pageSize)
                    ->select();
            } else {
                $list = Db::name('play')->alias('g')
                    ->join('chbc_shop s', "g.shop_no=s.shop_no")
                    ->field($field)
                    ->where($map)
                    ->where('g.user_pay-g.back_money<=5')
                    ->order($order)
                    ->group('g.shop_no')
                    ->page($page, $pageSize)
                    ->select();
            }
        } else {

            if ($snatchable) {
                $list = Db::name('play')->alias('g')
                    ->join('chbc_shop s', "g.shop_no=s.shop_no")
                    ->field($field)
                    ->where($map)
                    ->where('CONCAT_WS(" ",DATE_FORMAT(NOW(),"%Y-%m-%d"),g.end_time_str)>="'.date('Y-m-d H:i').'"')
                    ->order($order)
                    ->group('g.shop_no')
                    ->page($page, $pageSize)
                    ->select();
            } else {
                $list = Db::name('play')->alias('g')
                    ->join('chbc_shop s', "g.shop_no=s.shop_no")
                    ->field($field)
                    ->where($map)
                    ->order($order)
                    ->group('g.shop_no')
                    ->page($page, $pageSize)
                    ->select();
            }
        }
        $playObj = (new Play());
        $shopObj = (new Shop());
        foreach ($list as $k => $v) {
            $list[$k]['id'] = $v['play_no'];
            unset($list[$k]['play_no']);
            // 虚拟销量
            // $v['virtual_num'] = $v['num'];
            // $list[$k]['num'] = $v['num']+$v['virtual_num'];
            $list[$k]['stock'] = $list[$k]['chbcquota'];
            // $list[$k]['distance_text'] = isset($distance_arr[$k])?$distance_arr[$k]:'0km';
            $v['distance'] = $this->get_distance([$lat,$lng],[$v['lat'],$v['lng']]);
            $list[$k]['distance_text'] = $v['distance']>1000?round($v['distance']/1000,2).'km':$v['distance'].'m';
            $list[$k]['back_money_text'] = $playObj->getBackMoneyTextAttr('',$v);
            $list[$k]['img_url'] = $playObj->getImgUrlAttr('',$v);
            $list[$k]['scheme_no_text'] = $playObj->getSchemeNoTextAttr('',$v);
            $list[$k]['play_label_text'] = $playObj->getPlayLabelTextAttr('',$v);
            if ($list[$k]['play_label_text']=='正常活动' || $list[$k]['play_label_text']=='新用户专享') {
                $list[$k]['play_label_text'] = '';
            }
            $v['shop_type'] = $v['s_type'];
            $list[$k]['shop_name'] = $v['s_name'];
            $list[$k]['shop_type'] = $v['s_type'];
            $list[$k]['shop_type_text'] = $shopObj->getShopTypeTextAttr('',$v);
            $list[$k]['now_time'] = $nowTime;
            $start_time_str = strtotime(date('Ymd').' '.$v['start_time_str']);
            $end_time_str = strtotime(date('Ymd').' '.$v['end_time_str']);
            if ($nowDateTime>$end_time_str) {
                $list[$k]['seize_order_status'] = '已结束';
            } elseif ($v['stock']==0) {
                $list[$k]['seize_order_status'] = '抢光了';
            } elseif ($end_time_str>=$nowDateTime && $nowDateTime>=$start_time_str) {
                $list[$k]['seize_order_status'] = '去抢单';
            } elseif ($start_time_str-$nowDateTime<=1800) {
                $list[$k]['seize_order_status'] = '超前抢';
            } elseif ($start_time_str-$nowDateTime>1800) {
                $list[$k]['seize_order_status'] = '未开始';
            }
            $map2 = $map;
            $map2['g.shop_no'] = $v['shop_no'];
            if ($snatchable) {
                $mutile = Db::name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")->field($field)->where($map2)->where('CONCAT_WS(" ",DATE_FORMAT(NOW(),"%Y-%m-%d"),g.end_time_str)>="'.date('Y-m-d H:i').'"')->select();
            } else {
                $mutile = Db::name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")->field($field)->where($map2)->select();
            }
            foreach ($mutile as $key => $value) {
                $mutile[$key]['id'] = $value['play_no'];
                unset($mutile[$key]['play_no']);
                // 虚拟销量
                // $value['virtual_num'] = $value['num'];
                // $mutile[$key]['num'] = $value['num']+$value['virtual_num'];
                $mutile[$key]['stock'] = $mutile[$key]['chbcquota'];
                $mutile[$key]['back_money_text'] = $playObj->getBackMoneyTextAttr('',$value);
                $mutile[$key]['play_label_text'] = $playObj->getPlayLabelTextAttr('',$value);
                $mutile[$key]['scheme_no_text'] = $playObj->getSchemeNoTextAttr('',$value);
                $start_time_str = strtotime(date('Ymd').' '.$value['start_time_str']);
                $end_time_str = strtotime(date('Ymd').' '.$value['end_time_str']);
                $mutile[$key]['seize_order_status'] = '';
                if ($nowDateTime>$end_time_str) {
                    $mutile[$key]['seize_order_status'] = '已结束';
                } elseif ($value['stock']==0) {
                    $mutile[$key]['seize_order_status'] = '抢光了';
                } elseif ($end_time_str>=$nowDateTime && $nowDateTime>=$start_time_str) {
                    $mutile[$key]['seize_order_status'] = '去抢单';
                } elseif ($start_time_str-$nowDateTime<=1800) {
                    $mutile[$key]['seize_order_status'] = '超前抢';
                } elseif ($start_time_str-$nowDateTime>1800) {
                    $mutile[$key]['seize_order_status'] = '未开始';
                }
            }
            $list[$k]['mutile'] = $mutile;
        }
        if ($high_rebate) {
            if ($snatchable) {
                $count = Db::name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")
                ->field($field)
                ->where($map)
                ->where('CONCAT_WS(" ",DATE_FORMAT(NOW(),"%Y-%m-%d"),g.end_time_str)>="'.date('Y-m-d H:i').'"')
                ->where('g.user_pay-g.back_money<=5')
                ->group('g.shop_no')
                ->count();
            } else {
                $count = Db::name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")
                ->field($field)
                ->where($map)
                ->where('g.user_pay-g.back_money<=5')
                ->group('g.shop_no')
                ->count();
            }
        } else {
            if ($snatchable) {
                $count = Db::name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")
                ->field($field)
                ->where($map)
                ->where('CONCAT_WS(" ",DATE_FORMAT(NOW(),"%Y-%m-%d"),g.end_time_str)>="'.date('Y-m-d H:i').'"')
                ->group('g.shop_no')
                ->count();
            } else {
                $count = Db::name('play')->alias('g')
                ->join('chbc_shop s', "g.shop_no=s.shop_no")
                ->field($field)
                ->where($map)
                ->group('g.shop_no')
                ->count();
            }
        }
        $lastPage = $count / $pageSize >= (int)$count / $pageSize ? (int)($count / $pageSize) + 1 : (int)($count / $pageSize);
        if (!$list) $list = [];
        if (!$lastPage) $lastPage = 0;
        if (!$count) $count = 0;
        return ['last_page' => $lastPage, 'total' => $count, 'list' => $list];


    }

    public function getPlayDetail($play_no = 0)
    {
        $playObj = new Play();
        $nowDateTime = time();
        $nowTime = $nowDateTime - strtotime(date("Y-m-d 00:00:00", $nowDateTime));
        $play = $playObj->alias('p')->join('chbc_shop s','s.shop_no=p.shop_no')->field("p.*,s.id as shop_id,s.phone,s.lat,s.lng,s.address,s.logo_pic,s.address,sp.qrcode_pic,sp.platform_no,sp.is_xls,sp.elm_appenter,sp.sku as skuList,s.dpzxelm,s.is_sjzp,s.province,s.city,s.area,s.has_qrcode,s.shop_name as sshop_name")->join('chbc_shop_platform sp','sp.shop_no=s.shop_no')->where('p.play_no', $play_no)
            ->find();
        if ($play) {
            $play = $play->toArray();
            // 虚拟销量
            // $play['virtual_num'] = $play['num'];
            // $play['num'] = $play['num']+$play['virtual_num'];
            $play['shop_name'] = $play['sshop_name'];
            $play['stock'] = $play['chbcquota'];
            $play['now_time'] = $nowTime;
            $play['img_url'] = $playObj->getImgUrlAttr('',$play);
            $play['play_type'] = Play::getPlayTypeAttr($play['play_type'],$play);
            $play['channel'] = 'bdb';
            $play['id'] = $play['play_no'];
            $play['logo_pic_url'] = strpos($play['logo_pic'],'://')===false?config('upload_domain').$play['logo_pic']:$play['logo_pic'];
            $qrcode_pic = explode(',', $play['qrcode_pic']);
            foreach ($qrcode_pic as $key => $value) {
                $play['qrcode_pic'] = strpos($value,'://')===false?config('upload_domain').$value:$value;
            }
            $play['skuList'] = str_replace('&quot;', '"', $play['skuList']);
            $play['skuList'] = json_decode($play['skuList'],1);
            unset($play['logo_pic']);
            unset($play['play_no']);
            unset($play['super_play_no']);
        }
        return $play;
    }

    /**
     * [shopDistance description]
     * @param  [type]  $data type=1,计算列表，type==2，计算单个距离
     * @param  [type]  $lng  [description]
     * @param  [type]  $lat  [description]
     * @param  integer $type [description]
     * @return [type]        [description]
     */
    public static function shopDistance($data,$lng,$lat,$type=1)
    {
        $distance_arr = [];
        if ($type==1) {
            $list = $data;
        } else {
            $list = [$data];
        }
            $txmapurlbase = 'https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling&key='.config('txmap_key').'&from='.$lat.','.$lng;
            if (count($list)>0) {
                $to = '';
                foreach ($list as $lk => $lv) {
                    $to .= $lv['lat'].','.$lv['lng'].';';
                }
                $to = trim($to,';');
                if ($to) {
                    $txmapurl = $txmapurlbase.'&to='.$to;
                    $res = file_get_contents($txmapurl);
                    $decode = json_decode($res,1);
                    if ($decode['status']==0) {
                        foreach ($decode['result']['rows'][0]['elements'] as $dk => $dv) {
                            $distance_arr[] = $dv['distance'] > 1000 ? numberFormat($dv['distance'] / 1000) . "km" : $dv['distance'] . "m";
                        }
                    }
                }
            }
        // } else {
        //     $txmapurl = 'https://apis.map.qq.com/ws/direction/v1/bicycling/?key='.config('txmap_key').'&from='.$lat.','.$lng.'&to='.$data['lat'].','.$data['lng'];
        //     $res = file_get_contents($txmapurl);
        //     var_dump($res);exit;
        //     $decode = json_decode($res,1);
        //     if ($decode['status']==0) {
        //         $distance = $decode['result']['routes'][0]['distance'];
        //         $distance_arr[] = $distance > 1000 ? numberFormat($distance / 1000) . "km" : $distance . "m";
        //     }
        // }
        return $distance_arr;
    }


    public function updateStock($content,$play_id,$poiEventId)
    {
        Db::startTrans();
        // try {
            foreach ($content['plan_list'] as $key => $valuess) {
                if ($poiEventId==$valuess['plan_id']) {
                    $stock = $valuess['rest_stock']>1?$valuess['rest_stock']-1:0;
                    $content['plan_list'][$key]['rest_stock'] = $stock;
                }
            }
            $update = Db::name('mtofficial')->where('id',$play_id)->update(['content'=>json_encode($content)]);
            Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     return false;
        // }
        // return true;
    }
    public static function get_distance($from,$to,$decimal=2){  
        sort($from);  
        sort($to); 
        $EARTH_RADIUS = 6378.138; // 地球半径系数  
        
        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;  
        return round($distance, $decimal);  
        // $distance_arr = [];
        // $txmapurl = 'https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling&key='.config('txmap_key').'&from='.$from[0].','.$from[1].'&to='.$to[0].','.$to[1];
        // $res = file_get_contents($txmapurl);
        // $decode = json_decode($res,1);
        // if ($decode['status']==0) {
        //     foreach ($decode['result']['rows'][0]['elements'] as $dk => $dv) {
        //         $distance_arr[] = $dv['distance'];
        //     }
        // }
        // return $distance_arr[0];
    } 
}